# -*- coding = utf-8 -*-
# @Time : 2023/2/20 17:41
# @Author : 龙王赘婿_彪少
# @File : com.py
# @Software: PyCharm

# 功能：串口

import serial
from time import sleep


class Mycom:
    def __init__(self):
        self.ser = serial.Serial(timeout=10)
        self.port_open_recv()
        while True:
            # a = input(">")
            # print("send")
            # self.send(a)

            print("read")
            # self.read()
            # self.read2()
            self.read3()
            # sleep(0.5)

    def port_open_recv(self):
        self.ser.port = 'com6'
        self.ser.baudrate = 115200
        self.ser.bytesize = 8
        self.ser.stopbits = 1
        self.ser.parity = 'N'
        self.ser.open()
        if (self.ser.isOpen()):
            print("串口打开成功！")
        else:
            print("串口打开失败")

    def port_close(self):
        self.ser.close()
        if (self.ser.isOpen()):
            print("串口关闭成功！")
        else:
            print("串口关闭失败")

    def send(self, send_data):
        if (self.ser.isOpen()):
            self.ser.write(send_data.encode('utf-8'))
            print(f"发送成功：{send_data}")
        else:
            print("发送失败")

    def read(self):
        if (self.ser.isOpen()):
            recv_data = self.ser.read_all()
            temp = recv_data.decode("utf-8")
            print(f"接收成功：{temp}")
        else:
            print("发送失败")

    def read2(self):
        if (self.ser.isOpen()):
            recv_data = self.ser.read(1024)
            temp = recv_data.decode("utf-8")
            print(f"接收成功：{temp}")
        else:
            print("发送失败")

    def read3(self):
        if (self.ser.isOpen()):
            recv_data = self.ser.readline()
            temp = recv_data.decode("utf-8")
            print(f"接收成功：{temp}")
        else:
            print("发送失败")


if __name__ == "__main__":
    com = Mycom()
